<template>
	<div class='fx'>
		<p class='f12 g9 lh22'>( 使用向下 " ↓ " 箭头自动搜索 )</p>
	</div>
	<dl ref='listRef' class='abs_lb bcf f12 oys scrollbar w dn' :style="{ maxHeight:200, zIndex:100, boxShadow:'0 0 5px #ddd', border:'1px solid ' + fn.c0}">
		<dd v-for='(v,i) of ajax.data' :key='i' class='omits-1 h30 plr10 cp linear' :class="[index === i ? 'bcm cf' : 'hover tap']" @click='onSelect($event, i,v)'>{{v.content}}</dd>
		<dd v-if='ajax.loading' class='f12 g9 tc ptb5'>加载中...</dd>
		<dd v-if='!ajax.loading && fn.hasArray(data)' class='f12 g9 tc ptb5'>加载中...</dd>
	</dl>
</template>

<script setup>
	import { onMounted } from 'vue'
	/* --------------------------- props --------------------------- */
	const { dom, value } = defineProps({
		data: { type:Array, default:[] },
		dom: Object,
		value: String
	})
	
	const emit = defineEmits(['select'])
	
	const fn = $fn
	
	let listRef = $ref()
	
	let ajax = $ref({ data:[], loading:false })
	let index = $ref(1)
	
	const onSelect = (e, i, { content }) => {
		index = i
		e.stopPropagation()
		content = $fn.isValid(value) ? value + '\r' + content : content
		emit('select', content)
	}
	
	// 显示与隐藏
	const hide = () => listRef.style.display = 'none'
	const show = () => listRef.style.display = 'block'
	
	const onListener = e => {
		const { data } = ajax
		const len =  data.length
		e.preventDefault()
		if(e.keyCode === 40){
			if(index < len - 1 ){
				index ++
			}else {
				index = 0
			}
		}else if(e.keyCode === 38){
			console.log(index)
			if(index > 0 ){
				index --
			}else {
				index = len-1
			}
		}else if(e.keyCode === 13){
			if(listRef.style.display !== 'none'){
				const content = data[index]?.content
				onSelect(e, index, { content } )
			}
		}
	}
	// 按下方向键，显示列表
	let first
	const onResult = e => {
		if(e.keyCode === 40){
			show()
		
			$http.pull(ajax, 'expertStore.quickReply', { param:{ type: 1 } }).then(rs=>{
				window.addEventListener('keyup', onListener)
			})
			
			if(!first){
				window.addEventListener('click', hide )
				first = true
			}
			listRef.style.bottom = (dom.clientHeight) + 'px'
			
			dom.blur()
		}
	}
	
	window.removeEventListener('click', hide )
	window.removeEventListener('keyup', onListener)
	
	
	onMounted(()=>{
		dom.addEventListener('keyup', onResult)
	})
</script>
